package com.interesting;

import java.util.HashMap;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.interesting.client.UI.home.Hot_PicFragment;
import com.interesting.client.UI.home.MenuFragment;
import com.interesting.client.UI.home.RecentFragment;
import com.interesting.client.UI.home.SendMesgActivity;
import com.interesting.client.UI.user.MyCollectFragment;
import com.interesting.client.UI.user.MyCommentFragment;
import com.interesting.client.UI.user.MyNewsFragment;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;

public class MainActivity extends SlidingFragmentActivity {

	private long touchTime = 0;
	private long waitTime = 2000;

	private ActionBar actionBar;
	private RadioButton first, second;
	private static SlidingMenu sm;
	public FragmentsManager fManager;
	private int hot=0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		setTheme(R.style.Theme_Sherlock_Light);
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		actionBar = getSupportActionBar();
		actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.bluebg));
		actionBar.setIcon(R.drawable.ic_sliding_actionbar_logo);
		actionBar.setCustomView(R.layout.two_radio_actionbar_custom_view);

		first = (RadioButton) actionBar.getCustomView().findViewById(R.id.two_radio_bar_first);
		second = (RadioButton) actionBar.getCustomView().findViewById(R.id.two_radio_bar_second);
		first.setText("干货");
		first.setTag("0");
		second.setText("嫩草");
		second.setTag("1");

		actionBar.setDisplayShowCustomEnabled(true);
		actionBar.setHomeButtonEnabled(true);
		getWindow().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.bg_color)));

		sm = getSlidingMenu();
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);

		setContentView(R.layout.main_content_frame);
		setBehindContentView(R.layout.main_menu_frame);

		sm.setShadowDrawable(R.drawable.sliding_shadow_bg);
		sm.setShadowWidthRes(R.dimen.slidingmenu_shadow_width_15);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset); // 打开menu后 content宽度

		sm.setFadeDegree(0.1f);

		fManager = new FragmentsManager(this, R.id.main_frame_content);
		fManager.addFragment("hot", Hot_PicFragment.class, null);
		fManager.addFragment("recent", RecentFragment.class, null);
		fManager.addFragment("picture", Hot_PicFragment.class, null);
		fManager.addFragment("mycomment", MyCommentFragment.class, null);
		fManager.addFragment("mymessage", MyNewsFragment.class, null);
		fManager.addFragment("mycollect", MyCollectFragment.class, null);
		fManager.changFragment("hot");
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem item = menu.add(Menu.NONE, R.id.menu_edit, Menu.NONE, "投稿");
		item.setIcon(R.drawable.edit_mesg_ic);
		item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			toggle();
			return true;
		case R.id.menu_edit:
			Intent intent = new Intent(MainActivity.this, SendMesgActivity.class);
			startActivity(intent);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) {
			long currentTime = System.currentTimeMillis();
			if ((currentTime - touchTime) >= waitTime) {
				Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
				touchTime = currentTime;
			} else {
				finish();
				System.exit(0);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void toActivity(Intent intent) {
		startActivityForResult(intent, 1);// 在登录后 方便获取用户名
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		switch (resultCode) {
		case -1:
			MenuFragment menuFragment = (MenuFragment) getSupportFragmentManager().findFragmentById(
					R.id.main_activity_menu);
			if (menuFragment != null)
				menuFragment.onActivityResult(requestCode, resultCode, intent);
			break;
		/** 信息详情界面发生变化 则更新数据 */
		case 21:
			Fragment fragment = null;
			fragment = getSupportFragmentManager().findFragmentById(R.id.main_frame_content);
			fragment.onActivityResult(requestCode, resultCode, intent);
			break;
		case 10:
			MenuFragment menu = (MenuFragment) getSupportFragmentManager().findFragmentById(
					R.id.main_activity_menu);
			menu.onActivityResult(requestCode, resultCode, intent);
		}
		super.onActivityResult(requestCode, requestCode, intent);
	}

	/**
	 * 管理一级页面的Fragment，防止重复生成
	 * 
	 * @author beanu
	 * 
	 */
	public static class FragmentsManager {
		private final FragmentActivity mActivity;
		// private final TabHost mTabHost;
		private final int mContainerId;
		private final HashMap<String, FragmentInfo> mTabs = new HashMap<String, FragmentInfo>();
		FragmentInfo mLastFragment;

		static final class FragmentInfo {
			private final String tag;
			private final Class<?> clss;
			private final Bundle args;
			private Fragment fragment;

			FragmentInfo(String _tag, Class<?> _class, Bundle _args) {
				tag = _tag;
				clss = _class;
				args = _args;
			}
		}

		/**
		 * 
		 * @param activity
		 *            依附的主Activity
		 * @param containerId
		 *            填充Fragment的id
		 */
		public FragmentsManager(FragmentActivity activity, int containerId) {
			mActivity = activity;
			mContainerId = containerId;
		}

		public void addFragment(String tag, Class<?> clss, Bundle args) {

			FragmentInfo info = new FragmentInfo(tag, clss, args);

			// Check to see if we already have a fragment for this tab, probably
			// from a previously saved state. If so, deactivate it, because our
			// initial state is that a tab isn't shown.
			info.fragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag);
			if (info.fragment != null && !info.fragment.isDetached()) {
				FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
				ft.detach(info.fragment);
				ft.commit();
			}

			mTabs.put(tag, info);
		}

		public void changFragment(String tag) {

			FragmentInfo newTab = mTabs.get(tag);
			if (mLastFragment != newTab) {
				FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
				if (mLastFragment != null) {
					if (mLastFragment.fragment != null) {
						ft.detach(mLastFragment.fragment);
					}
				}
				if (newTab != null) {
					if (newTab.fragment == null) {
						newTab.fragment = Fragment.instantiate(mActivity, newTab.clss.getName(), newTab.args);
						ft.add(mContainerId, newTab.fragment, newTab.tag);
					} else {
						ft.attach(newTab.fragment);
					}
				}

				mLastFragment = newTab;
				ft.commit();
				mActivity.getSupportFragmentManager().executePendingTransactions();
				sm.showContent();
			} else {
				sm.showContent();
			}

		}
	}

	/** 设置标题 */
	public void setTitle(String title) {
		getSupportActionBar().setCustomView(R.layout.text_only_actionbar_custom_view);
		TextView tv = (TextView) getSupportActionBar().getCustomView().findViewById(R.id.text_action_bar_view_title);
		tv.setText(title);
		super.setTitle(title);
	}

}
